<script lang="tsx">
/**
 * 树型组件
 */
export default {
  name: "tree-form"
}
</script>

<script lang="tsx" setup>
import TreeManager from "./tree-manager.ts"
import {ref, watch} from "vue"
import {cloneDeep} from "lodash"

/**
 * 定义props
 */
const props = withDefaults(
    defineProps<{
      tree: TreeManager
    }>(),
    {
      tree() {
        return {
          props: {
            defaultExpand: false
          },
          prop: {
            children: "items",
            label: "label",
            parentNode: "superiorId"
          },
          data: [],
          defaultExpand: false
        }
      }
    }
)

/**
 * 定义emit
 */
const emit = defineEmits<{
  (e: "node-click", node: any): void
  (e: "node-update", node: any): void
}>()

/**
 * 组件实例
 */
const treeRef = ref()

/**
 * 组件数据
 */
const treeData = ref()

/**
 * 点击节点
 */
const handleNodeClick = (node: any) => {
  if (props.tree.event?.nodeClick) {
    props.tree.event.nodeClick(node)
  }
}

/**
 * 节点拖动事件
 */
const handleNodeDrop = (draggingNode: Node, dropNode: Node, type: string) => {
  if (props.tree.event?.nodeDrop) {
    props.tree.event.nodeDrop(draggingNode, dropNode, type)
  }
}

/**
 * 节点收起事件
 */
const handleExpandChange = (draggingNode: Node) => {
  console.log(draggingNode)
}

/**
 * 获取数据
 */
const getTreeData = () => {
  return treeData.value
}

/**
 * 设置数据
 */
const setTreeData = (data: any) => {
  treeData.value = cloneDeep(data)
}

/**
 * 获取当前选中的节点
 */
const getCurrentNode = () => {
  return treeRef.value.getCurrentNode()
}

/**
 * 渲染
 */
const renderFn = (data: any) => {
  return treeData.value.renderFn(data.data)
}

/**
 * 监听数据更新
 */
watch(() => props.tree, (newValue: any) => {
  if (newValue) {
    treeData.value = newValue
  }
}, {
  deep: true,
  immediate: true
})

/**
 * 暴露
 */
defineExpose({
  getTreeData,
  setTreeData,
  getCurrentNode
})
</script>

<template>
  <el-tree
      ref="treeRef"
      :data="treeData.data"
      :default-expand-all="tree?.props?.defaultExpand"
      :draggable="true"
      :props="treeData.prop"
      @node-click="handleNodeClick"
      @node-drop="handleNodeDrop"
      @node-collapse="handleExpandChange"
  >
    <template v-if="treeData.renderFn" #default="{ node,data }">
      <renderFn :data="data"/>
    </template>
  </el-tree>
</template>

<style lang="scss" scoped>

</style>